import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:xrenovation/api/contractors.api.dart';
import 'package:xrenovation/localization/app_localizations.dart';
import 'package:xrenovation/utils/message_util.dart';
import 'package:xrenovation/widgets/custom_app_bar.dart';
import 'package:xrenovation/widgets/custom_button.dart';
import 'package:xrenovation/widgets/custom_text_field.dart';
import 'package:xrenovation/widgets/header_box.dart';
import 'package:xrenovation/widgets/shadow_card.dart';

class ContractorsPage extends StatefulWidget {
  const ContractorsPage({super.key});

  @override
  State<ContractorsPage> createState() => _ContractorsPageState();
}

class _ContractorsPageState extends State<ContractorsPage> {
  List<dynamic> contractors = [];
  List<dynamic> skills = [];
  bool isLoading = true;
  bool _isAddingContractor = false;
  bool _isUpdatingContractor = false;
  bool _isAddingSkill = false;
  final bool _isLoadingReviews = false;
  final attention = Color(0xFF00B8DB);
  File? _selectedImage;
  final ImagePicker _picker = ImagePicker();
  bool _isImageLoading = false;

  @override
  Widget build(BuildContext context) {
    final localizations = AppLocalizations.of(context);
    final theme = Theme.of(context);

    return HeaderBox(
      child: Scaffold(
        appBar: CustomAppBar(
          title: localizations.translate('contractors_page_title'),
          actionName: localizations.translate('add_contractor'),
          actionIcon: Icons.add,
          action: () => _showAddContractorDialog(theme, localizations),
        ),
        body: GestureDetector(
          onTap: () => FocusScope.of(context).unfocus(),
          behavior: HitTestBehavior.opaque,
          child:
              isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : contractors.isEmpty
                  ? Center(
                    child: Text(
                      localizations.translate('no_contractors'),
                      style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
                      textAlign: TextAlign.center,
                    ),
                  )
                  : SingleChildScrollView(
                    padding: const EdgeInsets.symmetric(vertical: 10),
                    child: Column(
                      children: [
                        for (var contractor in contractors)
                          Padding(
                            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 20),
                            child: _buildContractorCard(contractor, localizations, theme),
                          ),
                        const SizedBox(height: 50),
                      ],
                    ),
                  ),
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  Widget _buildContractorCard(dynamic contractor, AppLocalizations localizations, ThemeData theme) {
    final isDarkMode = theme.brightness == Brightness.dark;
    return ShadowCard(
      onTap: () => _showContractorReviews(contractor, localizations),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
            width: 64,
            height: 64,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(32),
              color: theme.colorScheme.secondary.withOpacity(0.1),
            ),
            child:
                contractor['avatarUrl'] != null
                    ? ClipRRect(
                      borderRadius: BorderRadius.circular(32),
                      child: Image.network(
                        contractor['avatarUrl'],
                        fit: BoxFit.cover,
                        errorBuilder: (_, __, ___) => _buildDefaultAvatar(theme, isDarkMode, 32),
                      ),
                    )
                    : _buildDefaultAvatar(theme, isDarkMode, 32),
          ),
          const SizedBox(width: 20),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${contractor['firstName']} ${contractor['lastName']}',
                            style: theme.textTheme.titleMedium?.copyWith(fontWeight: FontWeight.w600, height: 1.2),
                          ),
                        ],
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        IconButton(
                          icon: const Icon(Icons.edit, size: 22),
                          padding: const EdgeInsets.all(8),
                          onPressed: () => _showEditContractorDialog(contractor, localizations),
                        ),
                        IconButton(
                          icon: const Icon(Icons.delete, size: 22),
                          padding: const EdgeInsets.all(8),
                          onPressed: () => _showDeleteDialog(contractor['id'], localizations),
                        ),
                      ],
                    ),
                  ],
                ),
                const SizedBox(height: 10),
                if (contractor['preferredName'] != null && contractor['preferredName'] != '') ...[
                  Text(
                    '${localizations.translate('preferred_name_label')}: ${contractor['preferredName'] ?? ''}',
                    style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                  ),
                  const SizedBox(height: 10),
                ],
                if (contractor['companyName'] != null && contractor['companyName'] != '') ...[
                  Text(contractor['companyName'], style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor)),
                  const SizedBox(height: 10),
                ],
                Text(
                  contractor['phoneNumber'] ?? '',
                  style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                ),
                const SizedBox(height: 10),
                if (contractor['email'] != null && contractor['email'] != '') ...[
                  Row(
                    children: [
                      Icon(Icons.email, size: 16, color: theme.hintColor),
                      const SizedBox(width: 10),
                      Text(
                        contractor['email'] ?? '',
                        style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                ],
                if (contractor['address'] != null && contractor['address'] != '') ...[
                  Row(
                    children: [
                      Icon(Icons.location_on, size: 16, color: theme.hintColor),
                      const SizedBox(width: 10),
                      Expanded(
                        child: Text(
                          contractor['address'] ?? '',
                          style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 10),
                ],
                Text(
                  '${localizations.translate('skills')}:',
                  style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                ),
                const SizedBox(height: 6),
                Wrap(
                  spacing: 6,
                  runSpacing: 6,
                  children: [
                    for (var skill in contractor['skills'] ?? [])
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                        decoration: BoxDecoration(
                          // color: theme.colorScheme.primary,
                          color: attention,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          skill['name'],
                          style: theme.textTheme.bodySmall?.copyWith(color: theme.colorScheme.onPrimary),
                        ),
                      ),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildDefaultAvatar(ThemeData theme, bool isDarkMode, double? size) {
    return Icon(
      Icons.person,
      size: size ?? 32,
      color: isDarkMode ? theme.colorScheme.outline : theme.colorScheme.outlineVariant.withOpacity(0.5),
    );
  }

  Widget _buildRatingItem(ThemeData theme, String label, double value) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor)),
          const SizedBox(height: 8),
          Row(
            children: [
              const Icon(Icons.star, size: 20, color: Color(0xFFFDC700)),
              const SizedBox(width: 10),
              Text(value.toStringAsFixed(1), style: theme.textTheme.bodyMedium),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildReviewRatingItem(ThemeData theme, String label, int value) {
    return Expanded(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(label, style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor)),
          const SizedBox(height: 8),
          Row(
            children: [
              const Icon(Icons.star, size: 20, color: Color(0xFFFDC700)),
              const SizedBox(width: 10),
              Text('$value/5', style: theme.textTheme.bodyMedium),
            ],
          ),
        ],
      ),
    );
  }

  Future<void> _loadData() async {
    setState(() => isLoading = true);
    try {
      final contractorsRes = await ContractorsApi.getContractorList();
      final skillsRes = await ContractorsApi.getSkillList();

      if (mounted) {
        setState(() {
          contractors = contractorsRes['data'] ?? [];
          skills = skillsRes['data'] ?? [];
          isLoading = false;
        });
      }
    } catch (e) {
      if (mounted) {
        setState(() => isLoading = false);
        MessageUtil.error('Failed to load contractors');
      }
    }
  }

  Future<File?> _pickImage(ImageSource source) async {
    try {
      final pickedFile = await _picker.pickImage(source: source, maxWidth: 800, imageQuality: 85);
      return pickedFile != null ? File(pickedFile.path) : null;
    } catch (e) {
      MessageUtil.error('Failed to pick image: ${e.toString()}');
      return null;
    }
  }

  void _showAddContractorDialog(ThemeData theme, AppLocalizations localizations) {
    final formKey = GlobalKey<FormState>();
    final firstNameController = TextEditingController();
    final lastNameController = TextEditingController();
    final preferredNameController = TextEditingController();
    final companyNameController = TextEditingController();
    final phoneController = TextEditingController();
    final emailController = TextEditingController();
    final addressController = TextEditingController();
    final taxIdController = TextEditingController();
    final skillNameController = TextEditingController();
    final isDarkMode = theme.brightness == Brightness.dark;
    final List<String> selectedSkillIds = [];

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              behavior: HitTestBehavior.opaque,
              child: Container(
                // height: MediaQuery.of(context).size.height * 0.9,
                padding: const EdgeInsets.all(24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                localizations.translate('add_new_contractor'),
                                style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                localizations.translate('fill_contractor_info'),
                                style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                              ),
                            ],
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.close),
                          onPressed: () {
                            Navigator.pop(context);
                            _selectedImage = null;
                          },
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),
                    Expanded(
                      child: SingleChildScrollView(
                        child: Form(
                          key: formKey,
                          child: Column(
                            children: [
                              Center(
                                child: Container(
                                  width: 100,
                                  height: 100,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(50),
                                    color: theme.colorScheme.secondary.withOpacity(0.1),
                                    // color: isDarkMode ? theme.cardColor : theme.colorScheme.surfaceContainerHighest,
                                  ),
                                  child:
                                      _selectedImage != null
                                          ? ClipRRect(
                                            borderRadius: BorderRadius.circular(50),
                                            child: Image.file(_selectedImage!, fit: BoxFit.cover),
                                          )
                                          : _buildDefaultAvatar(theme, isDarkMode, 50),
                                ),
                              ),
                              const SizedBox(height: 20),
                              Center(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    SizedBox(
                                      width: 136,
                                      child: CustomButton(
                                        title: localizations.translate('upload_photos'),
                                        height: 42,
                                        isLoading: _isImageLoading,
                                        onTap: () async {
                                          if (_isImageLoading) return;
                                          setState(() => _isImageLoading = true);
                                          final img = await _pickImage(ImageSource.gallery);
                                          if (img != null) {
                                            setState(() => _selectedImage = img);
                                          }
                                          setState(() => _isImageLoading = false);
                                        },
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 136,
                                      child: CustomButton(
                                        title: localizations.translate('use_camera'),
                                        height: 42,
                                        isLoading: _isImageLoading,
                                        onTap: () async {
                                          if (_isImageLoading) return;
                                          setState(() => _isImageLoading = true);
                                          final img = await _pickImage(ImageSource.camera);
                                          if (img != null) {
                                            setState(() => _selectedImage = img);
                                          }
                                          setState(() => _isImageLoading = false);
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 24),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: firstNameController,
                                      keyboardType: TextInputType.name,
                                      label: localizations.translate('first_name'),
                                      labelMark: true,
                                      hintText: localizations.translate('first_name'),
                                      hiddenErrorTip: true,
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          return '';
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: CustomTextField(
                                      controller: lastNameController,
                                      keyboardType: TextInputType.name,
                                      label: localizations.translate('last_name'),
                                      hintText: localizations.translate('last_name'),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: preferredNameController,
                                label: localizations.translate('preferred_name'),
                                keyboardType: TextInputType.name,
                                hintText: localizations.translate('preferred_name'),
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: companyNameController,
                                keyboardType: TextInputType.name,
                                label: localizations.translate('company_name'),
                                hintText: localizations.translate('company_name'),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: phoneController,
                                      label: localizations.translate('phone_number'),
                                      labelMark: true,
                                      hintText: localizations.translate('phone_number'),
                                      keyboardType: TextInputType.phone,
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          // return '';
                                          return localizations.translate('phone_required');
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: emailController,
                                      keyboardType: TextInputType.emailAddress,
                                      label: localizations.translate('email'),
                                      hintText: localizations.translate('email'),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: addressController,
                                keyboardType: TextInputType.multiline,
                                label: localizations.translate('address'),
                                hintText: localizations.translate('address'),
                                maxLines: 3,
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: taxIdController,
                                label: localizations.translate('ein_ssn'),
                                hintText: localizations.translate('ein_ssn'),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Text(
                                    '${localizations.translate('skills')} *',
                                    style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 6),
                              Wrap(
                                spacing: 10,
                                runSpacing: 10,
                                children: [
                                  for (var skill in skills)
                                    GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (selectedSkillIds.contains(skill['id'])) {
                                            selectedSkillIds.remove(skill['id']);
                                          } else {
                                            selectedSkillIds.add(skill['id']);
                                          }
                                        });
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        decoration: BoxDecoration(
                                          color:
                                              selectedSkillIds.contains(skill['id'])
                                                  ? attention
                                                  : theme.colorScheme.surfaceContainerHighest,
                                          borderRadius: BorderRadius.circular(4),
                                        ),
                                        child: Text(
                                          skill['name'],
                                          style: theme.textTheme.bodySmall?.copyWith(
                                            color:
                                                selectedSkillIds.contains(skill['id'])
                                                    ? theme.colorScheme.onPrimary
                                                    : theme.colorScheme.onSurface,
                                          ),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              GestureDetector(
                                onTap: () {
                                  _showAddSkillDialog(skillNameController, setState, selectedSkillIds, localizations);
                                },
                                child: Row(
                                  children: [
                                    Icon(Icons.add, size: 16, color: theme.colorScheme.primary),
                                    const SizedBox(width: 4),
                                    Text(
                                      localizations.translate('add_new_skill'),
                                      style: TextStyle(color: theme.colorScheme.primary),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 40),
                              CustomButton(
                                title: localizations.translate('save_changes'),
                                isLoading: _isAddingContractor,
                                onTap: () async {
                                  if (formKey.currentState?.validate() ?? false) {
                                    if (selectedSkillIds.isEmpty) {
                                      MessageUtil.toast(localizations.translate('select_at_least_one_skill'));
                                      return;
                                    }

                                    setState(() => _isAddingContractor = true);
                                    try {
                                      final res = await ContractorsApi.updateContractor(
                                        url: '/contractor/add',
                                        data: {
                                          'firstName': firstNameController.text,
                                          'lastName': lastNameController.text,
                                          'preferredName': preferredNameController.text,
                                          'companyName': companyNameController.text,
                                          'phoneNumber': phoneController.text,
                                          'email': emailController.text,
                                          'address': addressController.text,
                                          'taxId': taxIdController.text,
                                          'skillIds': selectedSkillIds.join(','),
                                        },
                                        imageFile: _selectedImage,
                                      );

                                      if (res['code'] == 200) {
                                        MessageUtil.success(localizations.translate('contractor_added_successfully'));
                                        Navigator.pop(context);
                                        _selectedImage = null;
                                        _loadData();
                                      } else {
                                        MessageUtil.error(res['message']);
                                      }
                                    } catch (e) {
                                      MessageUtil.error(localizations.translate('failed_to_add_contractor'));
                                    } finally {
                                      if (mounted) {
                                        setState(() => _isAddingContractor = false);
                                      }
                                    }
                                  }
                                },
                              ),
                              const SizedBox(height: 10),
                              CustomButton(
                                title: localizations.translate('cancel'),
                                isOutlined: true,
                                onTap: () {
                                  Navigator.pop(context);
                                  _selectedImage = null;
                                },
                              ),
                              const SizedBox(height: 40),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }

  void _showAddSkillDialog(
    TextEditingController controller,
    StateSetter setState,
    List<String> selectedSkillIds,
    AppLocalizations localizations,
  ) {
    final formKey = GlobalKey<FormState>();
    final theme = Theme.of(context);

    showDialog(
      context: context,
      builder: (context) {
        return Dialog(
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16.0)),
          elevation: 0,
          backgroundColor: Colors.transparent,
          child: Container(
            padding: const EdgeInsets.all(24),
            decoration: BoxDecoration(color: theme.colorScheme.surface, borderRadius: BorderRadius.circular(16)),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  localizations.translate('add_new_skill'),
                  style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                ),
                const SizedBox(height: 16),
                Form(
                  key: formKey,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      CustomTextField(
                        controller: controller,
                        label: localizations.translate('skill_name'),
                        hintText: localizations.translate('skill_name_hint'),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            // return '';
                            return localizations.translate('field_required');
                          }
                          return null;
                        },
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),
                Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    TextButton(
                      onPressed: () => Navigator.pop(context),
                      style: TextButton.styleFrom(padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8)),
                      child: Text(
                        localizations.translate('cancel'),
                        style: theme.textTheme.labelLarge?.copyWith(color: theme.colorScheme.onSurface),
                      ),
                    ),
                    const SizedBox(width: 8),
                    ElevatedButton(
                      onPressed: () async {
                        if (formKey.currentState?.validate() ?? false) {
                          setState(() => _isAddingSkill = true);
                          final closeLoading = MessageUtil.loading(localizations.translate('adding_skill'));
                          try {
                            final res = await ContractorsApi.addSkill(controller.text);
                            if (res['code'] == 200) {
                              MessageUtil.success(localizations.translate('skill_added_successfully'));
                              Navigator.pop(context);
                              controller.clear();
                              final skillsRes = await ContractorsApi.getSkillList();
                              setState(() {
                                skills = skillsRes['data'] ?? [];
                              });
                            } else {
                              MessageUtil.error(res['message']);
                            }
                          } catch (e) {
                            MessageUtil.error(localizations.translate('failed_to_add_skill'));
                          } finally {
                            setState(() => _isAddingSkill = false);
                            closeLoading();
                          }
                        }
                      },
                      style: ElevatedButton.styleFrom(
                        backgroundColor: theme.colorScheme.primary,
                        foregroundColor: theme.colorScheme.onPrimary,
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
                      ),
                      child:
                          _isAddingSkill
                              ? const SizedBox(
                                width: 20,
                                height: 20,
                                child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
                              )
                              : Text(
                                localizations.translate('confirm'),
                                style: theme.textTheme.labelLarge?.copyWith(color: theme.colorScheme.onPrimary),
                              ),
                    ),
                  ],
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  void _showContractorReviews(dynamic contractor, AppLocalizations localizations) {
    List<dynamic> reviews = [];
    bool isLoading = true;
    double workQualityAvg = 0;
    double workSpeedAvg = 0;
    double costEffectivenessAvg = 0;
    final theme = Theme.of(context);

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            if (isLoading) {
              ContractorsApi.getContractorReviews(contractor['id']).then((res) {
                if (res['code'] == 200) {
                  reviews = res['data'] ?? [];
                  if (reviews.isNotEmpty) {
                    workQualityAvg =
                        reviews.map((r) => r['workQuality'] as int).reduce((a, b) => a + b) / reviews.length;
                    workSpeedAvg = reviews.map((r) => r['workSpeed'] as int).reduce((a, b) => a + b) / reviews.length;
                    costEffectivenessAvg =
                        reviews.map((r) => r['costEffectiveness'] as int).reduce((a, b) => a + b) / reviews.length;
                  }
                  setState(() => isLoading = false);
                }
              });
            }

            return Container(
              height: MediaQuery.of(context).size.height * 0.8,
              padding: const EdgeInsets.all(24),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        child: Text(
                          localizations
                              .translate('reviews_title')
                              .replaceAll('{name}', '${contractor['firstName']} ${contractor['lastName']}'),
                          style: theme.textTheme.titleLarge,
                        ),
                      ),
                      IconButton(icon: const Icon(Icons.close), onPressed: () => Navigator.pop(context)),
                    ],
                  ),
                  const SizedBox(height: 20),
                  Expanded(
                    child:
                        isLoading
                            ? const Center(child: CircularProgressIndicator())
                            : reviews.isEmpty
                            ? Center(
                              child: Text(
                                localizations.translate('no_reviews_yet'),
                                style: theme.textTheme.bodyLarge?.copyWith(color: theme.hintColor),
                              ),
                            )
                            : SingleChildScrollView(
                              child: Column(
                                children: [
                                  ShadowCard(
                                    color: theme.cardColor.withOpacity(0.5),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Text(
                                          localizations.translate('average_ratings'),
                                          style: theme.textTheme.titleMedium,
                                        ),
                                        const SizedBox(height: 20),
                                        Row(
                                          mainAxisAlignment: MainAxisAlignment.start,
                                          children: [
                                            _buildRatingItem(
                                              theme,
                                              localizations.translate('work_quality'),
                                              workQualityAvg,
                                            ),
                                            _buildRatingItem(
                                              theme,
                                              localizations.translate('work_speed'),
                                              workSpeedAvg,
                                            ),
                                            _buildRatingItem(
                                              theme,
                                              localizations.translate('cost_effectiveness'),
                                              costEffectivenessAvg,
                                            ),
                                          ],
                                        ),
                                      ],
                                    ),
                                  ),
                                  const SizedBox(height: 20),
                                  for (var review in reviews)
                                    Padding(
                                      padding: const EdgeInsets.only(bottom: 20),
                                      child: ShadowCard(
                                        child: Column(
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Text(review['name'], style: theme.textTheme.bodyMedium),
                                            const SizedBox(height: 6),
                                            Text(
                                              localizations
                                                  .translate('completed_on')
                                                  .replaceAll(
                                                    '{date}',
                                                    review['completionDate'].split('T')[0].replaceAll('-', '/'),
                                                  ),
                                              style: theme.textTheme.bodySmall?.copyWith(color: theme.hintColor),
                                            ),
                                            const SizedBox(height: 20),
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                              children: [
                                                _buildReviewRatingItem(
                                                  theme,
                                                  localizations.translate('quality'),
                                                  review['workQuality'],
                                                ),
                                                _buildReviewRatingItem(
                                                  theme,
                                                  localizations.translate('speed'),
                                                  review['workSpeed'],
                                                ),
                                                _buildReviewRatingItem(
                                                  theme,
                                                  localizations.translate('value'),
                                                  review['costEffectiveness'],
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                            ),
                  ),
                ],
              ),
            );
          },
        );
      },
    );
  }

  void _showDeleteDialog(String id, AppLocalizations localizations) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(localizations.translate('delete_confirm_title')),
          content: Text(localizations.translate('delete_confirm_content')),
          actions: [
            TextButton(onPressed: () => Navigator.pop(context), child: Text(localizations.translate('cancel'))),
            TextButton(
              onPressed: () async {
                final closeLoading = MessageUtil.loading(localizations.translate('Loading'));
                try {
                  final res = await ContractorsApi.deleteContractor(id);
                  if (res['code'] == 200) {
                    MessageUtil.success(localizations.translate('delete_success'));
                    Navigator.pop(context);
                    _loadData();
                  } else {
                    MessageUtil.error(res['message']);
                  }
                } catch (e) {
                  MessageUtil.error(localizations.translate('failed_to_delete_contractor'));
                } finally {
                  closeLoading();
                }
              },
              child: Text(
                localizations.translate('delete'),
                style: TextStyle(color: Theme.of(context).colorScheme.error),
              ),
            ),
          ],
        );
      },
    );
  }

  void _showEditContractorDialog(dynamic contractor, AppLocalizations localizations) {
    final theme = Theme.of(context);
    final formKey = GlobalKey<FormState>();
    final firstNameController = TextEditingController(text: contractor['firstName']);
    final lastNameController = TextEditingController(text: contractor['lastName']);
    final preferredNameController = TextEditingController(text: contractor['preferredName']);
    final companyNameController = TextEditingController(text: contractor['companyName']);
    final phoneController = TextEditingController(text: contractor['phoneNumber']);
    final emailController = TextEditingController(text: contractor['email']);
    final addressController = TextEditingController(text: contractor['address']);
    final taxIdController = TextEditingController(text: contractor['taxId']);
    final skillNameController = TextEditingController();
    final isDarkMode = theme.brightness == Brightness.dark;
    final List<String> selectedSkillIds =
        (contractor['skills'] as List?)?.map((s) => s['id'].toString()).toList() ?? [];

    showModalBottomSheet(
      context: context,
      isScrollControlled: true,
      builder: (context) {
        return StatefulBuilder(
          builder: (context, setState) {
            return GestureDetector(
              onTap: () => FocusScope.of(context).unfocus(),
              behavior: HitTestBehavior.opaque,
              child: Container(
                // height: MediaQuery.of(context).size.height * 0.9,
                padding: const EdgeInsets.all(24),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                localizations.translate('edit_contractor'),
                                style: theme.textTheme.titleLarge?.copyWith(fontWeight: FontWeight.w600),
                              ),
                              const SizedBox(height: 4),
                              Text(
                                localizations.translate('edit_contractor_info'),
                                style: theme.textTheme.bodyMedium?.copyWith(color: theme.hintColor),
                              ),
                            ],
                          ),
                        ),
                        IconButton(
                          icon: const Icon(Icons.close),
                          onPressed: () {
                            Navigator.pop(context);
                            _selectedImage = null;
                          },
                        ),
                      ],
                    ),
                    const SizedBox(height: 24),
                    Expanded(
                      child: SingleChildScrollView(
                        child: Form(
                          key: formKey,
                          child: Column(
                            children: [
                              Center(
                                child: Container(
                                  width: 100,
                                  height: 100,
                                  decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(50),
                                    color: theme.colorScheme.secondary.withOpacity(0.1),
                                    // color: isDarkMode ? theme.cardColor : theme.colorScheme.surfaceContainerHighest,
                                  ),
                                  child:
                                      _selectedImage != null
                                          ? ClipRRect(
                                            borderRadius: BorderRadius.circular(50),
                                            child: Image.file(_selectedImage!, fit: BoxFit.cover),
                                          )
                                          : contractor['avatarUrl'] != null
                                          ? ClipRRect(
                                            borderRadius: BorderRadius.circular(50),
                                            child: Image.network(
                                              contractor['avatarUrl'],
                                              fit: BoxFit.cover,
                                              errorBuilder: (_, __, ___) => _buildDefaultAvatar(theme, isDarkMode, 50),
                                            ),
                                          )
                                          : _buildDefaultAvatar(theme, isDarkMode, 50),
                                ),
                              ),
                              const SizedBox(height: 20),
                              Center(
                                child: Row(
                                  mainAxisSize: MainAxisSize.min,
                                  children: [
                                    SizedBox(
                                      width: 136,
                                      child: CustomButton(
                                        title: localizations.translate('upload_photos'),
                                        height: 42,
                                        isLoading: _isImageLoading,
                                        onTap: () async {
                                          if (_isImageLoading) return;
                                          setState(() => _isImageLoading = true);
                                          final img = await _pickImage(ImageSource.gallery);
                                          if (img != null) {
                                            setState(() => _selectedImage = img);
                                          }
                                          setState(() => _isImageLoading = false);
                                        },
                                      ),
                                    ),
                                    const SizedBox(width: 10),
                                    SizedBox(
                                      width: 136,
                                      child: CustomButton(
                                        title: localizations.translate('use_camera'),
                                        height: 42,
                                        isLoading: _isImageLoading,
                                        onTap: () async {
                                          if (_isImageLoading) return;
                                          setState(() => _isImageLoading = true);
                                          final img = await _pickImage(ImageSource.camera);
                                          if (img != null) {
                                            setState(() => _selectedImage = img);
                                          }
                                          setState(() => _isImageLoading = false);
                                        },
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 24),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: firstNameController,
                                      keyboardType: TextInputType.name,
                                      label: localizations.translate('first_name'),
                                      labelMark: true,
                                      hintText: localizations.translate('first_name'),
                                      hiddenErrorTip: true,
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          return '';
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                  const SizedBox(width: 20),
                                  Expanded(
                                    child: CustomTextField(
                                      controller: lastNameController,
                                      keyboardType: TextInputType.name,
                                      label: localizations.translate('last_name'),
                                      hintText: localizations.translate('last_name'),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: preferredNameController,
                                label: localizations.translate('preferred_name'),
                                keyboardType: TextInputType.name,
                                hintText: localizations.translate('preferred_name'),
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: companyNameController,
                                keyboardType: TextInputType.name,
                                label: localizations.translate('company_name'),
                                hintText: localizations.translate('company_name'),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: phoneController,
                                      label: localizations.translate('phone_number'),
                                      labelMark: true,
                                      hintText: localizations.translate('phone_number'),
                                      keyboardType: TextInputType.phone,
                                      validator: (value) {
                                        if (value == null || value.isEmpty) {
                                          // return '';
                                          return localizations.translate('phone_required');
                                        }
                                        return null;
                                      },
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Expanded(
                                    child: CustomTextField(
                                      controller: emailController,
                                      keyboardType: TextInputType.emailAddress,
                                      label: localizations.translate('email'),
                                      hintText: localizations.translate('email'),
                                    ),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: addressController,
                                keyboardType: TextInputType.multiline,
                                label: localizations.translate('address'),
                                hintText: localizations.translate('address'),
                                maxLines: 3,
                              ),
                              const SizedBox(height: 16),
                              CustomTextField(
                                controller: taxIdController,
                                label: localizations.translate('ein_ssn'),
                                hintText: localizations.translate('ein_ssn'),
                              ),
                              const SizedBox(height: 16),
                              Row(
                                children: [
                                  Text(
                                    '${localizations.translate('skills')} *',
                                    style: theme.textTheme.bodyMedium?.copyWith(fontWeight: FontWeight.w500),
                                  ),
                                ],
                              ),
                              const SizedBox(height: 6),
                              Wrap(
                                spacing: 10,
                                runSpacing: 10,
                                children: [
                                  for (var skill in skills)
                                    GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          if (selectedSkillIds.contains(skill['id'])) {
                                            selectedSkillIds.remove(skill['id']);
                                          } else {
                                            selectedSkillIds.add(skill['id']);
                                          }
                                        });
                                      },
                                      child: Container(
                                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
                                        decoration: BoxDecoration(
                                          color:
                                              selectedSkillIds.contains(skill['id'])
                                                  ? theme.colorScheme.primary
                                                  : theme.colorScheme.surfaceContainerHighest,
                                          borderRadius: BorderRadius.circular(4),
                                        ),
                                        child: Text(
                                          skill['name'],
                                          style: theme.textTheme.bodySmall?.copyWith(
                                            color:
                                                selectedSkillIds.contains(skill['id'])
                                                    ? theme.colorScheme.onPrimary
                                                    : theme.colorScheme.onSurface,
                                          ),
                                        ),
                                      ),
                                    ),
                                ],
                              ),
                              const SizedBox(height: 16),
                              GestureDetector(
                                onTap: () {
                                  _showAddSkillDialog(skillNameController, setState, selectedSkillIds, localizations);
                                },
                                child: Row(
                                  children: [
                                    Icon(Icons.add, size: 16, color: theme.colorScheme.primary),
                                    const SizedBox(width: 4),
                                    Text(
                                      localizations.translate('add_new_skill'),
                                      style: TextStyle(color: theme.colorScheme.primary),
                                    ),
                                  ],
                                ),
                              ),
                              const SizedBox(height: 40),
                              CustomButton(
                                title: localizations.translate('save_changes'),
                                isLoading: _isUpdatingContractor,
                                onTap: () async {
                                  if (formKey.currentState?.validate() ?? false) {
                                    if (selectedSkillIds.isEmpty) {
                                      MessageUtil.toast(localizations.translate('select_at_least_one_skill'));
                                      return;
                                    }

                                    setState(() => _isUpdatingContractor = true);
                                    try {
                                      final res = await ContractorsApi.updateContractor(
                                        url: '/contractor/update',
                                        data: {
                                          'id': contractor['id'],
                                          'firstName': firstNameController.text,
                                          'lastName': lastNameController.text,
                                          'preferredName': preferredNameController.text,
                                          'companyName': companyNameController.text,
                                          'phoneNumber': phoneController.text,
                                          'email': emailController.text,
                                          'address': addressController.text,
                                          'taxId': taxIdController.text,
                                          'skillIds': selectedSkillIds.join(','),
                                        },
                                        imageFile: _selectedImage,
                                      );

                                      if (res['code'] == 200) {
                                        MessageUtil.success(localizations.translate('contractor_updated_successfully'));
                                        Navigator.pop(context);
                                        _selectedImage = null;
                                        _loadData();
                                      } else {
                                        MessageUtil.error(res['message']);
                                      }
                                    } catch (e) {
                                      MessageUtil.error(localizations.translate('failed_to_update_contractor'));
                                    } finally {
                                      if (mounted) {
                                        setState(() => _isUpdatingContractor = false);
                                      }
                                    }
                                  }
                                },
                              ),
                              const SizedBox(height: 10),
                              CustomButton(
                                title: localizations.translate('cancel'),
                                isOutlined: true,
                                onTap: () {
                                  Navigator.pop(context);
                                  _selectedImage = null;
                                },
                              ),
                              const SizedBox(height: 40),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            );
          },
        );
      },
    );
  }
}
